#!/usr/bin/env python3
"""
Shopify权限验证助手
用于验证新生成的访问令牌是否具有正确的权限
"""

import os
import sys
import asyncio
import logging
from typing import Dict, List, Optional, Any

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from dotenv import load_dotenv
load_dotenv()

try:
    import shopify
except ImportError:
    print("❌ 未安装Shopify API库，请运行: pip install shopifyapi")
    sys.exit(1)

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('shopify_permission_checker')


class ShopifyPermissionChecker:
    """Shopify权限检查器"""
    
    def __init__(self):
        self.api_key = os.getenv("SHOPIFY_API_KEY", "")
        self.api_secret = os.getenv("SHOPIFY_API_SECRET", "")
        self.store_url = os.getenv("SHOPIFY_STORE_URL", "")
        self.access_token = os.getenv("SHOPIFY_ACCESS_TOKEN", "")
        
        # 必需权限列表
        self.required_permissions = [
            "read_products",
            "read_orders", 
            "write_products",
            "read_customers",
            "read_inventory"
        ]
        
        # 推荐权限列表
        self.recommended_permissions = [
            "write_orders",
            "read_analytics",
            "read_themes"
        ]
    
    def validate_config(self) -> Dict[str, Any]:
        """验证配置完整性"""
        logger.info("🔍 检查配置完整性...")
        
        missing_configs = []
        if not self.api_key:
            missing_configs.append("SHOPIFY_API_KEY")
        if not self.api_secret:
            missing_configs.append("SHOPIFY_API_SECRET")
        if not self.store_url:
            missing_configs.append("SHOPIFY_STORE_URL")
        if not self.access_token:
            missing_configs.append("SHOPIFY_ACCESS_TOKEN")
        
        # 检查URL格式
        url_issues = []
        if self.store_url and not self.store_url.endswith('.myshopify.com'):
            url_issues.append(f"商店URL格式不正确: {self.store_url}")
        
        return {
            "complete": len(missing_configs) == 0,
            "missing": missing_configs,
            "url_issues": url_issues,
            "config_summary": {
                "api_key_configured": bool(self.api_key),
                "api_secret_configured": bool(self.api_secret),
                "store_url_configured": bool(self.store_url),
                "access_token_configured": bool(self.access_token)
            }
        }
    
    async def test_api_connection(self) -> Dict[str, Any]:
        """测试API连接"""
        logger.info("🔌 测试API连接...")
        
        try:
            # 设置会话
            shopify.Session.setup(api_key=self.api_key, secret=self.api_secret)
            
            # 测试不同API版本
            api_versions = ["2024-10", "2024-07", "2023-10"]
            best_version = None
            connection_success = False
            shop_info = None
            
            for version in api_versions:
                try:
                    logger.info(f"  测试API版本 {version}...")
                    
                    session = shopify.Session(self.store_url, version, self.access_token)
                    shopify.ShopifyResource.activate_session(session)
                    
                    # 测试获取商店信息
                    shop = shopify.Shop.current()
                    shop_info = {
                        "name": shop.name,
                        "domain": shop.domain,
                        "myshopify_domain": shop.myshopify_domain,
                        "email": shop.email,
                        "country": shop.country,
                        "currency": shop.currency
                    }
                    
                    logger.info(f"  ✅ API版本 {version} 连接成功")
                    logger.info(f"     商店名称: {shop.name}")
                    logger.info(f"     商店域名: {shop.domain}")
                    
                    best_version = version
                    connection_success = True
                    
                    # 清理会话
                    shopify.ShopifyResource.clear_session()
                    break
                    
                except Exception as e:
                    logger.warning(f"  ❌ API版本 {version} 连接失败: {str(e)}")
                    try:
                        shopify.ShopifyResource.clear_session()
                    except:
                        pass
                    continue
            
            return {
                "success": connection_success,
                "best_version": best_version,
                "shop_info": shop_info,
                "error": None if connection_success else "所有API版本连接失败"
            }
            
        except Exception as e:
            logger.error(f"API连接测试失败: {str(e)}")
            return {
                "success": False,
                "best_version": None,
                "shop_info": None,
                "error": str(e)
            }
    
    async def check_product_permissions(self, api_version: str) -> Dict[str, Any]:
        """检查产品权限"""
        logger.info("📦 检查产品访问权限...")
        
        try:
            session = shopify.Session(self.store_url, api_version, self.access_token)
            shopify.ShopifyResource.activate_session(session)
            
            # 测试获取产品列表
            products = shopify.Product.find(limit=5)
            
            # 测试创建产品（仅测试权限，不实际创建）
            can_create = False
            try:
                # 尝试创建一个测试产品（会立即删除）
                test_product = shopify.Product()
                test_product.title = "权限测试产品"
                test_product.body_html = "这是一个权限测试产品"
                test_product.product_type = "测试产品"
                test_product.status = "draft"  # 草稿状态，不会显示在前台
                
                # 不实际保存，只检查是否有权限
                # 这里我们假设如果有读权限，通常也有写权限
                can_create = True
            except Exception:
                can_create = False
            
            # 清理会话
            shopify.ShopifyResource.clear_session()
            
            return {
                "success": True,
                "product_count": len(products),
                "can_read": True,
                "can_create": can_create,
                "sample_products": [
                    {
                        "id": p.id,
                        "title": p.title,
                        "status": p.status
                    } for p in products[:3]
                ]
            }
            
        except Exception as e:
            logger.error(f"产品权限检查失败: {str(e)}")
            try:
                shopify.ShopifyResource.clear_session()
            except:
                pass
            
            return {
                "success": False,
                "product_count": 0,
                "can_read": False,
                "can_create": False,
                "error": str(e)
            }
    
    async def check_order_permissions(self, api_version: str) -> Dict[str, Any]:
        """检查订单权限"""
        logger.info("📋 检查订单访问权限...")
        
        try:
            session = shopify.Session(self.store_url, api_version, self.access_token)
            shopify.ShopifyResource.activate_session(session)
            
            # 测试获取订单列表
            orders = shopify.Order.find(limit=5, status="any")
            
            # 清理会话
            shopify.ShopifyResource.clear_session()
            
            return {
                "success": True,
                "order_count": len(orders),
                "can_read": True,
                "sample_orders": [
                    {
                        "id": o.id,
                        "name": o.name,
                        "financial_status": getattr(o, 'financial_status', 'unknown'),
                        "created_at": o.created_at
                    } for o in orders[:3]
                ]
            }
            
        except Exception as e:
            logger.error(f"订单权限检查失败: {str(e)}")
            try:
                shopify.ShopifyResource.clear_session()
            except:
                pass
            
            return {
                "success": False,
                "order_count": 0,
                "can_read": False,
                "error": str(e)
            }
    
    def generate_permission_report(self, test_results: Dict[str, Any]) -> None:
        """生成权限检查报告"""
        logger.info("\n" + "="*60)
        logger.info("📊 SHOPIFY权限检查报告")
        logger.info("="*60)
        
        # 配置检查
        config_check = test_results["config_check"]
        if not config_check["complete"]:
            logger.error("❌ 配置不完整，缺少以下配置:")
            for missing in config_check["missing"]:
                logger.error(f"   - {missing}")
            return
        
        # API连接检查
        connection_test = test_results["connection_test"]
        if not connection_test["success"]:
            logger.error("❌ API连接失败")
            logger.error(f"   错误: {connection_test['error']}")
            return
        
        logger.info(f"✅ API连接成功 (版本: {connection_test['best_version']})")
        logger.info(f"   商店: {connection_test['shop_info']['name']}")
        logger.info(f"   域名: {connection_test['shop_info']['myshopify_domain']}")
        
        # 权限检查
        logger.info("\n🔐 权限检查结果:")
        
        # 产品权限
        product_test = test_results["product_permissions"]
        if product_test["success"]:
            logger.info(f"✅ 产品权限: 正常")
            logger.info(f"   可读: {product_test['can_read']}")
            logger.info(f"   产品数量: {product_test['product_count']}")
            if product_test.get('sample_products'):
                logger.info("   示例产品:")
                for p in product_test['sample_products']:
                    logger.info(f"     - {p['title']} (ID: {p['id']})")
        else:
            logger.error(f"❌ 产品权限: 失败")
            logger.error(f"   错误: {product_test['error']}")
        
        # 订单权限
        order_test = test_results["order_permissions"]
        if order_test["success"]:
            logger.info(f"✅ 订单权限: 正常")
            logger.info(f"   可读: {order_test['can_read']}")
            logger.info(f"   订单数量: {order_test['order_count']}")
            if order_test.get('sample_orders'):
                logger.info("   示例订单:")
                for o in order_test['sample_orders']:
                    logger.info(f"     - {o['name']} (状态: {o['financial_status']})")
        else:
            logger.error(f"❌ 订单权限: 失败")
            logger.error(f"   错误: {order_test['error']}")
        
        # 建议
        logger.info("\n💡 建议:")
        if product_test["success"] and order_test["success"]:
            logger.info("✅ 所有权限正常，可以使用真实API数据")
            logger.info("   请确保在.env文件中设置:")
            logger.info("   SHOPIFY_FORCE_MOCK_MODE=false")
            logger.info("   SHOPIFY_DISABLE_MOCK_MODE=true")
        else:
            logger.warning("⚠️  权限不足，建议:")
            logger.warning("   1. 在Shopify后台重新生成访问令牌")
            logger.warning("   2. 确保启用所有必需权限:")
            for perm in self.required_permissions:
                logger.warning(f"      - {perm}")
            logger.warning("   3. 或暂时使用模拟数据模式:")
            logger.warning("      SHOPIFY_FORCE_MOCK_MODE=true")
        
        logger.info("\n" + "="*60)


async def main():
    """主函数"""
    print("🚀 Shopify权限验证助手")
    print("="*50)
    
    checker = ShopifyPermissionChecker()
    
    # 1. 验证配置
    config_check = checker.validate_config()
    if not config_check["complete"]:
        logger.error("配置验证失败，请检查环境变量")
        return
    
    # 2. 测试API连接
    connection_test = await checker.test_api_connection()
    if not connection_test["success"]:
        logger.error("API连接失败，请检查凭据")
        return
    
    # 3. 检查各项权限
    api_version = connection_test["best_version"]
    
    product_permissions = await checker.check_product_permissions(api_version)
    order_permissions = await checker.check_order_permissions(api_version)
    
    # 4. 生成报告
    test_results = {
        "config_check": config_check,
        "connection_test": connection_test,
        "product_permissions": product_permissions,
        "order_permissions": order_permissions
    }
    
    checker.generate_permission_report(test_results)


if __name__ == "__main__":
    asyncio.run(main())